package jp.ac.utokyo.pinyomi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class PinyinTable extends AbstractTable {
	private static PinyinTable instance;

	private PinyinTable() throws IOException {
		super();
	}

	public static synchronized PinyinTable getInstance() throws IOException {
		if (instance == null) {
			instance = new PinyinTable();
		}
		return instance;
	}

	@Override
	protected HashMap<String, Pair> readfile() throws IOException {
		System.out.println("Reading pinyin file ...");
		
		HashMap<String, Pair> map = new HashMap<String, Pair>();
		BufferedReader in = new BufferedReader(new InputStreamReader(
					new FileInputStream(Settings.GBKPinyinTable), "UTF-8"));
		String fieldSep = "\\s+";
		String strLine = null;
		
		while ((strLine = in.readLine()) != null) {
			strLine = strLine.trim();
			if (!"".equals(strLine)) {
				String[] fields = strLine.split(fieldSep);

				String mapkey = fields[0];
				
				// removing four tones (of Chinese).  ex. zhao1 and zhao3 will be counted only once to zhao
				ArrayList<String> pinyinList = new ArrayList<String>();
				for (int i=1; i< fields.length; i++){
					String p = fields[i].substring(0, fields[i].length()-1);
					if (!pinyinList.contains(p)) {
						pinyinList.add(p);
					}
				}

				Pair pair = new Pair();
				double prob = Math.log((1.0 / pinyinList.size()));
				for (String pinyin : pinyinList){
					pair.addPair(pinyin, prob);
				}

				map.put(mapkey, pair);
			}
		}
		return map;
	}
}


